package com.ctcf.ocr.engine.impl.utils;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class ImageClearUtils {

	/** 设置一个临界值，来界定该像素点，是否当作白色像素，即超过该值，都认为是白色 */
	private static int WHITE_COLOR_RGB_VALUE = 400;

	public static void main(String[] args) {
		String imageFilePath = "/Library/apache-tomcat-7.0.69/webapps/ocr.engine.web/WEB-INF/classes/testResources";
		try {
			BufferedImage image = ImageClearUtils.removeBackgroud(imageFilePath + "/ieta3s.jpg");
			ImageIO.write(image, "PNG", new File(imageFilePath + "/ieta3s_" + WHITE_COLOR_RGB_VALUE + ".png"));
			System.out.println("二值化处理完成！");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 判断是否为白色像素点
	 * 
	 * @param colorInt
	 * @return
	 */
	private static boolean isWhitePixel(int colorInt) {
		boolean isWhite = false;
		Color color = new Color(colorInt);
		// 设置一个临界值，来界定该像素点，是否当作白色像素，即超过该值，都认为是白色
		if (color.getRed() + color.getGreen() + color.getBlue() > ImageClearUtils.WHITE_COLOR_RGB_VALUE) {
			isWhite = true;
		}
		return isWhite;
	}

	/**
	 * 去除图片背景
	 * 
	 * @param imageFilePath
	 * @return
	 * @throws Exception
	 */
	public static BufferedImage removeBackgroud(String imageFilePath) throws Exception {
		BufferedImage img = ImageIO.read(new File(imageFilePath));
		return removeBackgroud(img);
	}

	/**
	 * 去除图片背景
	 * 
	 * @param imageFilePath
	 * @return
	 * @throws Exception
	 */
	public static BufferedImage removeBackgroud(File imageFile) throws Exception {
		BufferedImage img = ImageIO.read(imageFile);
		return removeBackgroud(img);
	}

	public static BufferedImage removeBackgroud(BufferedImage img) throws Exception {
		// BufferedImage img = ImageIO.read(new File(imageFilePath));
		int width = img.getWidth();
		int height = img.getHeight();
		for (int x = 0; x < width; ++x) {
			for (int y = 0; y < height; ++y) {
				boolean isWhite = isWhitePixel(img.getRGB(x, y));
				if (isWhite) {
					// 白色
					img.setRGB(x, y, Color.WHITE.getRGB());
				} else {
					// 黑色
					img.setRGB(x, y, Color.BLACK.getRGB());
				}
			}
		}
		return img;
	}
}
